import { Modal, Input, Button, message, InputRef } from 'antd';
import React, { useCallback, useRef, useState } from 'react';

import { useRequest2 } from '@/hooks/use-request';
import { t } from '@/locales/i18n';

export const useEditTitle = ({
  title,
  tip,
  placeholder = '',
  canEmpty = true,
  valueRule,
}: {
  title: string;
  tip?: string;
  placeholder?: string;
  canEmpty?: boolean;
  valueRule?: (val: string) => string | void;
}) => {
  const [isOpen, setIsOpen] = useState(false);

  const onOpen = useCallback(() => setIsOpen(true), []);
  const onClose = useCallback(() => setIsOpen(false), []);

  const inputRef = useRef<InputRef | null>(null);
  const onSuccessCb = useRef<(content: string) => void | Promise<void>>();
  const onErrorCb = useRef<(err: any) => void>();
  const defaultValue = useRef('');

  const onOpenModal = useCallback(
    ({
      defaultVal,
      onSuccess,
      onError,
    }: {
      defaultVal: string;
      onSuccess: (content: string) => any;
      onError?: (err: any) => void;
    }) => {
      onOpen();
      onSuccessCb.current = onSuccess;
      onErrorCb.current = onError;
      defaultValue.current = defaultVal;
    },
    [onOpen],
  );

  const onclickConfirm = useCallback(async () => {
    if (!inputRef.current || !onSuccessCb.current) return;
    const val = inputRef.current.input?.value;

    if (!canEmpty && !val) {
      inputRef.current.focus();
      return;
    }

    if (valueRule && val) {
      const result = valueRule(val);
      if (result) {
        message.warning(result);
        return;
      }
    }

    try {
      await onSuccessCb.current(val || '');
      onClose();
    } catch (err) {
      onErrorCb.current?.(err);
    }
  }, [canEmpty, onClose, valueRule]);

  // 使用useRequest2的钩子
  const { runAsync, loading } = useRequest2(onclickConfirm);

  // eslint-disable-next-line react/display-name
  const EditModal = useCallback(
    ({
      maxLength = 30,
      iconSrc = 'modal/edit',
      closeBtnText = t('common:common.Close'),
    }: {
      maxLength?: number;
      iconSrc?: string;
      closeBtnText?: string;
    }) => {
      return (
        <Modal
          title={title}
          open={isOpen}
          onCancel={onClose}
          footer={[
            closeBtnText && (
              <Button key="close" onClick={onClose}>
                {closeBtnText}
              </Button>
            ),
            <Button key="submit" type="primary" loading={loading} onClick={runAsync}>
              {t('common:common.Confirm')}
            </Button>,
          ]}
        >
          {tip && <p style={{ marginBottom: 8, color: '#999' }}>{tip}</p>}

          <Input
            ref={(el) => {
              inputRef.current = el;
            }}
            defaultValue={defaultValue.current}
            placeholder={placeholder}
            autoFocus
            maxLength={maxLength}
          />
        </Modal>
      );
    },
    [isOpen, onClose, loading, runAsync, placeholder, title, tip],
  );

  return {
    onOpenModal,
    EditModal,
  };
};
